#!/usr/bin/python3
import socket
import sys

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QPushButton, QGridLayout, QWidget, QMainWindow, \
    QMessageBox, QTableWidget, QTableWidgetItem, QHeaderView, QAbstractItemView

from panel_management_modules.console_functions import list_cmd, help_cmd
from panel_management_modules.nmcli import NetworkInterface

version = 1.0


class MyWindow(QMainWindow):

    def interface_setup(self) -> None:
        """
        Открывает окно настроек сети
        """
        try:
            self.network_interface_window.close()
        except Exception:
            print('Окно настройки сети не было активным')
        self.network_interface_window = NetworkInterface()
        self.network_interface_window.show()

    def run_command(self, console_mode: bool = False) -> None:
        """
        Отправляет команду на панель
        :param console_mode: запущена ли программа в консольном режиме
        :return: None
        """
        if console_mode:
            mode = sys.argv[1]
            if mode == 'run':
                if sys.argv[2] == '-c':
                    command = sys.argv[3]
                elif sys.argv[2] == '-n':
                    try:
                        command = self.commands[int(sys.argv[3]) - 1]
                    except IndexError:
                        print('Команды с указанным номером не существует')
                        return
                else:
                    print('Некорректный ввод')
                    help_cmd()
                    return
            else:
                if mode == 'list':
                    list_cmd()
                elif mode == 'help':
                    help_cmd()
                elif mode == 'setup':
                    temp_network_interface_window = NetworkInterface()
                    temp_network_interface_window.set_ip_in_console_mode()
                else:
                    print(f'Команда {mode} не поддерживается данной программой.')
                    help_cmd()
                return
        else:
            if self.commands_table.selectedItems():
                command = self.commands[self.commands_table.currentRow()].split()[0]
            else:
                return
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sock.sendto(bytes("F6" + command + "6F", "utf-8"), ("192.168.254.254", 8903))
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            sa = ("192.168.254.253", 8904)
            s.bind(sa)
            data, address = s.recvfrom(4096)
            s = data.decode('utf-8')
            if s[0:2] == "F6":
                s = s[6:-4]
                if len(s) > 4:
                    res = bytearray.fromhex(s).decode()
                else:
                    res = s
            else:
                res = "Ans: " + s
            res = f'Результат: {res}'
        except Exception as e:
            res = f'Возникло исключение: {e}'
        if not console_mode:
            dlg = QMessageBox()
            dlg.setWindowTitle('Информация')
            dlg.setText(res)
            dlg.exec_()
        else:
            print(res)

    def __init__(self):
        QMainWindow.__init__(self)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        grid = QGridLayout()
        central_widget.setLayout(grid)
        self.commands_table = QTableWidget()
        grid.addWidget(self.commands_table, 0, 0, 1, 2)

        all_commands_with_translation = open('commands', 'r').readlines()
        self.commands = [i.split(';')[0].strip() for i in all_commands_with_translation]
        self.translations = [i.split(';')[1].strip() for i in all_commands_with_translation]

        self.commands_table.setRowCount(len(self.commands))
        self.commands_table.setColumnCount(2)
        self.commands_table.setHorizontalHeaderLabels(['Команда', 'Перевод'])
        for row in range(len(self.commands)):
            self.commands_table.setItem(row, 0, QTableWidgetItem(self.commands[row]))
            if self.translations[row]:
                self.commands_table.setItem(row, 1, QTableWidgetItem(self.translations[row]))
        self.commands_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.commands_table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.commands_table.setSelectionMode(QAbstractItemView.SingleSelection)

        interface_button = QPushButton('Настроить интерфейс')
        interface_button.clicked.connect(self.interface_setup)
        grid.addWidget(interface_button, 1, 0)

        run_cmd_button = QPushButton('Отправить команду')
        run_cmd_button.clicked.connect(self.run_command)
        grid.addWidget(run_cmd_button, 1, 1)

        self.setGeometry(50, 50, 600, 500)
        self.setWindowTitle(f"Управление интерактивной панелью ver. {version}")
        self.setWindowIcon(QIcon(QIcon.fromTheme('panel-management')))


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(QIcon.fromTheme('panel-management')))
    window = MyWindow()
    if len(sys.argv) > 1:
        window.run_command(console_mode=True)
    else:
        window.show()
        sys.exit(app.exec_())
